//
//  AddBankCardVC.m
//  JinFuThree
//
//  Created by 毛韶谦 on 2018/9/6.
//  Copyright © 2018年 毛韶谦. All rights reserved.
//

#import "AddBankCardVC.h"
#import "HeaderBankCardView.h"
#import "ImportTextView.h"
#import "BankCardListVC.h"
#import "AATransitionVC.h"
#import "SCCaptureCameraController.h"
#import "MyRequestTools.h"

@interface AddBankCardVC ()<SCNavigationControllerDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,TZImagePickerControllerDelegate>

@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, strong) UIScrollView *mainScrollView;

@property (nonatomic, strong) HeaderBankCardView *headerCardView;

@property (nonatomic, strong) ImportTextView *nameView;
@property (nonatomic, strong) ImportTextView *identityView;
@property (nonatomic, strong) ImportTextView *cardNumberView;
@property (nonatomic, strong) ImportTextView *phoneView;

@property (nonatomic, strong) UIButton *nextBtn;
@property(nonatomic,strong)NSString *bankUrl;
@end

@implementation AddBankCardVC
{
    NSInteger recordCardCount;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initNavigationBar];
    [self initUI];
    // Do any additional setup after loading the view.
}

- (void)initNavigationBar {
    
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    
    UIView *backgroundView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 60, 44)];
    
    UIButton *button1 = [UIButton buttonWithType:UIButtonTypeSystem];
    [button1 setImage:[[UIImage imageNamed:@"BackArrow"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    button1.frame = CGRectMake(0, 2.5, 30, 41.5f);
    [button1 addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    
    [backgroundView addSubview:button1];
    
    UIButton *button2 = [UIButton buttonWithType:UIButtonTypeSystem];
    [button2 setImage:[[UIImage imageNamed:@"nav_close"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    button2.frame = CGRectMake(30, 2.5, 30, 41.5f);
    [button2 addTarget:self action:@selector(backRootAction) forControlEvents:UIControlEventTouchUpInside];
    
    [backgroundView addSubview:button2];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backgroundView];
}
- (void)backAction {
    
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)backRootAction {
    
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)initUI {
    
    self.title = @"添加银行卡";
    self.bankUrl = @"";
    self.mainScrollView.backgroundColor = ListMaoBackgroundColor;
    
    [self.headerCardView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(self.headerView);
        make.top.mas_equalTo(self.headerView.mas_bottom).offset(0.5f);
        make.height.mas_equalTo(165);
    }];
    
    [self.nameView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(self.headerView);
        make.top.mas_equalTo(self.headerCardView.mas_bottom).offset(10);
        make.height.mas_equalTo(50);
    }];
    [self.identityView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(self.headerView);
        make.top.mas_equalTo(self.nameView.mas_bottom);
        make.height.mas_equalTo(50);
    }];
    [self.cardNumberView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(self.headerView);
        make.top.mas_equalTo(self.identityView.mas_bottom);
        make.height.mas_equalTo(50);
    }];
    [self.phoneView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(self.headerView);
        make.top.mas_equalTo(self.cardNumberView.mas_bottom);
        make.height.mas_equalTo(50);
    }];
    
    [self.nextBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.headerView.mas_left).offset(20);
        make.right.mas_equalTo(self.headerView.mas_right).offset(-20);
        make.height.mas_equalTo(44);
        make.top.mas_equalTo(self.phoneView.mas_bottom).offset(56);
    }];
    
    UILabel *tinkLabel = [[UILabel alloc] init];
    tinkLabel.text = @"绑定的银行卡必须为本人所有";
    tinkLabel.textColor = HexColor(0x666666);
    tinkLabel.font = [UIFont systemFontOfSize:13];
    [self.mainScrollView addSubview:tinkLabel];
    [tinkLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.headerView.mas_left).offset(20);
        make.top.mas_equalTo(self.phoneView.mas_bottom).offset(15);
    }];
    
    UIButton *bankCardListBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [bankCardListBtn setTitle:@"查看支持银行卡" forState:UIControlStateNormal];
    [bankCardListBtn setTitleColor:ThemeMaoColor forState:UIControlStateNormal];
    bankCardListBtn.titleLabel.font = [UIFont systemFontOfSize:13];
    [bankCardListBtn addTarget:self action:@selector(bankCardListAction) forControlEvents:UIControlEventTouchUpInside];
    [self.mainScrollView addSubview:bankCardListBtn];
    [bankCardListBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(tinkLabel);
        make.right.mas_equalTo(self.headerView.mas_right).offset(-16);
        make.size.mas_equalTo(CGSizeMake(100, 19));
    }];
}

- (void)bankInfoWithPhone {
    
    SCCaptureCameraController *con = [[SCCaptureCameraController alloc] init];
    con.scNaigationDelegate = self;
    con.iCardType = TIDBANK;
    con.isDisPlayTxt = YES;
    [self presentViewController:con animated:YES completion:NULL];
}
- (void)uploadBankCardAction:(id)sender {
//    recordCardCount++;
//    if (recordCardCount > 3) {
        [self addImgFromPictureLibrary];
//    }else {
//        [self bankInfoWithPhone];
//    }
}
//- (void)bankInfoWithPhone {
//    SCCaptureCameraController *con = [[SCCaptureCameraController alloc] init];
//    con.scNaigationDelegate = self;
//    con.iCardType = TIDBANK;
//    con.isDisPlayTxt = YES;
//    [self presentViewController:con animated:YES completion:NULL];
//}
-(void)addImgFromPictureLibrary {
    UIAlertController * alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction * action0 = [UIAlertAction actionWithTitle:@"扫描拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self bankInfoWithPhone];
    }];
    [alert addAction:action0];
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIAlertAction * action1 = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self takePhotoSelectImgWithSourceType:UIImagePickerControllerSourceTypeCamera];
        }];
        [alert addAction:action1];
    }
    UIAlertAction * action2 = [UIAlertAction actionWithTitle:@"从相册中选取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self selectImgFromPhotoLibraryMaxImagesCount:1];
    }];
    UIAlertAction *cancelAction =[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    [alert addAction:action2];
    [alert addAction:cancelAction];
    [self presentViewController:alert animated:YES completion:nil];
}
-(void)takePhotoSelectImgWithSourceType:(UIImagePickerControllerSourceType)surceType {
    UIImagePickerController *imagePickerController =[[UIImagePickerController alloc]init];
    imagePickerController.delegate = self;
    imagePickerController.navigationBar.barTintColor = [UIColor whiteColor];
    imagePickerController.sourceType = surceType;
    [self presentViewController:imagePickerController animated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    UIImage *icon = [info objectForKey:UIImagePickerControllerOriginalImage];
    UIImageWriteToSavedPhotosAlbum(icon,nil,nil,nil);
    [self dealWithImg:icon];
    [picker dismissViewControllerAnimated:YES completion:nil];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}
-(void)selectImgFromPhotoLibraryMaxImagesCount:(NSInteger)maxImgesCount {
    TZImagePickerController *imgPickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:maxImgesCount delegate:self];
    imgPickerVc.allowPickingVideo = NO;
    imgPickerVc.allowPickingGif = NO;
    imgPickerVc.allowPickingMultipleVideo = NO;
//    imgPickerVc.naviBgColor = ThemeColor_NewJF;
    [imgPickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> * photos, NSArray *assets, BOOL result) {
        for (UIImage *image in photos)
        {
            [self dealWithImg:image];
        }
    }];
    [self presentViewController:imgPickerVc animated:YES completion:nil];
}
- (void)sendBankCardInfo:(NSString *)bank_num BANK_NAME:(NSString *)bank_name BANK_ORGCODE:(NSString *)bank_orgcode BANK_CLASS:(NSString *)bank_class CARD_NAME:(NSString *)card_name {
    NSLog(@"bank_num = %@, bank_name = %@, bank_orgcode = %@, bank_class = %@, card_name = %@",bank_num,bank_name,bank_orgcode,bank_class,card_name);
    self.cardNumberView.leftTextView.text = bank_num;
    
}
- (void)sendBankCardImage:(UIImage *)BankCardImage {
    NSLog(@"%@",BankCardImage);
    [self dealWithImg:BankCardImage];
}
- (void)dealWithImg:(UIImage *)image{

    [self uploadPictureWithimage:image];
}
-(void)uploadPictureWithimage:(UIImage *)image{

    [ASJF_Service uploadPictureWithData:image Success:^(id  _Nullable responseObject) {
        if (responseObject) {
            self.bankUrl = [[responseObject objectForKey:@"data"] objectForKey:@"filePath"];
            self.headerCardView.bankCardImageView.image = image;
            self.headerCardView.cameraImageView.hidden = YES;
            self.headerCardView.hintLabel.hidden = YES;
        }
        
    } Failure:^(id  _Nullable responseObject, NSError * _Nullable error) {
        self.headerCardView.cameraImageView.hidden = NO;
        self.headerCardView.hintLabel.hidden = NO;
    }];
//    [[RequestManager_NewJF manager] HFQUploadRequest:RequestMethodPost URLString:UploadPicURL parameters:nil file:file progress:^(int64_t totalUnitCount, int64_t completedUnitCount) {
//        [self showUploadAdvanceWithSpeed:1.0f *completedUnitCount / totalUnitCount with:[NSString stringWithFormat:@"%@上传中",@"银行卡照片"]];
//    } success:^(id  _Nullable responseObject) {
//        [self.hud hideAnimated:YES];
//        [self.hud removeFromSuperview];
//        self.hud = nil;
//        NSDictionary *dic = responseObject;
//        BOOL success = [dic[@"success"] boolValue];
//        if (success == YES) {
//            self.bankCardUrl = [dic[@"data"] objectForKey:@"filePath"];
//            [self.haveCardImageView sd_setImageWithURL:[NSURL URLWithString:self.bankCardUrl]];
//        }
//    } failure:^(id  _Nullable responseObject, NSError * _Nullable error) {
//        [self.hud hideAnimated:YES];
//        [self.hud removeFromSuperview];
//        self.hud = nil;
//        [HUD_NewJF showMessage:@"图片上传失败，请重新上传"];
//    }];
}

-(UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize {
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

- (void)bankCardListAction {
    
    BankCardListVC *vc = [[BankCardListVC alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

-(BOOL)checkPageContent{
    if ([self.bankUrl isEqualToString:@""]) {
        [HUD_Mao showCharacterMessage:@"请先上传银行卡照片"];
        return NO;
    }else if(![HFQCommonTools validateNickname:self.nameView.leftTextView.text]) {
        [HUD_Mao showCharacterMessage:@"请先输入正确的姓名"];
        return NO;
    }else if (![HFQCommonTools IsIdentityCard:self.identityView.leftTextView.text]){
        [HUD_Mao showCharacterMessage:@"请输入正确的身份证号"];
        return NO;
    }else if (![HFQCommonTools IsBankCard:self.cardNumberView.leftTextView.text]){
        [HUD_Mao showCharacterMessage:@"请输入正确的银行卡号"];
        return NO;
    }else if (![HFQCommonTools isValidateMobile:self.phoneView.leftTextView.text]){
        [HUD_Mao showCharacterMessage:@"请输入正确的手机号"];
        return NO;
    }else{
        return YES;
    }
}

- (void)tiJiaoAction {
//    if ([self checkPageContent] == YES) {
        NSDictionary *paramDic = [NSDictionary dictionaryWithObjectsAndKeys:self.bankUrl,@"bankCardImgUrl",self.nameView.leftTextView.text,@"ownerName",self.identityView.leftTextView.text,@"identityCardNumber",self.cardNumberView.leftTextView.text,@"bankCardnumber",self.phoneView.leftTextView.text,@"bankPhone", nil];
    NSMutableDictionary *param = [[NSMutableDictionary alloc]init];
    [param setObject:self.bankUrl forKey:@"bankCardImgUrl"];
    [param setObject:self.nameView.leftTextView.text forKey:@"ownerName"];
    [param setObject:self.identityView.leftTextView.text forKey:@"identityCardNumber"];
    [param setObject:self.cardNumberView.leftTextView.text forKey:@"bankCardnumber"];
    [param setObject:self.phoneView.leftTextView.text forKey:@"bankPhone"];
    
    
        
        [MyRequestTools addBankCardWithParameters:paramDic Success:^(id  _Nullable responseObject) {
            
            if ([[NSString stringWithFormat:@"%@",[responseObject objectForKey:@"code"]] isEqualToString:@"200"]) {
                [self.navigationController popViewControllerAnimated:YES];
            }
        } Failure:^(id  _Nullable responseObject, NSError * _Nullable error) {
        
        }];
        
      
//    }
    
    
}

- (UIScrollView *)mainScrollView {
    
    if (!_mainScrollView) {
        _mainScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidthMao, ScreenHeight - SafeAreaTopHeight)];
        _mainScrollView.contentSize = CGSizeMake(ScreenWidthMao, 600);
        _mainScrollView.showsVerticalScrollIndicator = NO;
        _mainScrollView.showsHorizontalScrollIndicator = NO;
        _mainScrollView.bounces = NO;
        
        [self.view addSubview:_mainScrollView];
    }
    return _mainScrollView;
}


- (UIView *)headerView {
    
    if (!_headerView) {
        _headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidthMao, 35)];
        _headerView.backgroundColor = ListMaoBackgroundColor;
        [self.mainScrollView addSubview:_headerView];
        
        
        UILabel *leftLabel = [[UILabel alloc] init];
        leftLabel.text = @"银行卡信息";
        leftLabel.textColor = HexColor(0x666666);
        leftLabel.font = [UIFont systemFontOfSize:13];
        [_headerView addSubview:leftLabel];
        [leftLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.mas_equalTo(_headerView);
            make.left.mas_equalTo(_headerView.mas_left).offset(20);
        }];
    }
    return _headerView;
}

- (UIButton *)nextBtn {
    
    if (!_nextBtn) {
        _nextBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _nextBtn.alpha = 0.5f;
        CAGradientLayer *gradientLayer = [CAGradientLayer layer];
        gradientLayer.colors = @[(__bridge id)HexColor(0xD6C096).CGColor, (__bridge id)HexColor(0xBEA471).CGColor];
        gradientLayer.locations = @[@0, @1];
        gradientLayer.startPoint = CGPointMake(0, 1);
        gradientLayer.endPoint = CGPointMake(1, 1);
        gradientLayer.frame = CGRectMake(0, 0, ScreenWidthMao - 40, 44);
        gradientLayer.cornerRadius = 4;
        gradientLayer.masksToBounds = YES;
        [_nextBtn.layer addSublayer:gradientLayer];
        [_nextBtn addTarget:self action:@selector(tiJiaoAction) forControlEvents:UIControlEventTouchUpInside];
        
        UILabel *label = [[UILabel alloc] init];
        label.font = [UIFont systemFontOfSize:15];
        label.textColor = [UIColor whiteColor];
        label.text = @"提交";
        [_nextBtn addSubview:label];
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.centerY.mas_equalTo(_nextBtn);
        }];
        
        [self.mainScrollView addSubview:_nextBtn];
    }
    return _nextBtn;
}

- (HeaderBankCardView *)headerCardView {
    
    if (!_headerCardView) {
        _headerCardView = [[HeaderBankCardView alloc] init];
        
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(uploadBankCardAction:)];
        [_headerCardView addGestureRecognizer:tapGesture];
        
        [self.mainScrollView addSubview:_headerCardView];
    }
    return _headerCardView;
}

- (ImportTextView *)nameView {
    
    if (!_nameView) {
        _nameView = [[ImportTextView alloc] init];
        _nameView.leftTextView.placeholder = @"持卡人名";
        _nameView.titleLabel.text = @"持卡人名";
        
        [self.mainScrollView addSubview:_nameView];
    }
    return _nameView;
}
- (ImportTextView *)identityView {
    
    if (!_identityView) {
        _identityView = [[ImportTextView alloc] init];
        _identityView.leftTextView.placeholder = @"18位身份证号";
        _identityView.titleLabel.text = @"身份证号";
        
        [self.mainScrollView addSubview:_identityView];
    }
    return _identityView;
}
- (ImportTextView *)cardNumberView {
    
    if (!_cardNumberView) {
        _cardNumberView = [[ImportTextView alloc] init];
        _cardNumberView.leftTextView.placeholder = @"请填写银行卡卡号";
        _cardNumberView.titleLabel.text = @"银行卡号";
        
        [self.mainScrollView addSubview:_cardNumberView];
    }
    return _cardNumberView;
}
- (ImportTextView *)phoneView {
    
    if (!_phoneView) {
        _phoneView = [[ImportTextView alloc] init];
        _phoneView.leftTextView.placeholder = @"请输入银行预留手机号";
        _phoneView.titleLabel.text = @"预留手机";
        [_phoneView.leftTextView setKeyboardType:UIKeyboardTypeNumberPad];
        _phoneView.lineImageView.hidden = YES;
        
        [self.mainScrollView addSubview:_phoneView];
    }
    return _phoneView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
